package com.tianyuan.lims.dms.controller.exam;

import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.tianyuan.lims.common.annotation.RequestBody;
import com.tianyuan.lims.common.render.InputStreamRender;
import com.tianyuan.lims.dms.controller.exam.entity.*;
import com.tianyuan.lims.dms.controller.exam.service.ExamRecordService;
import com.tianyuan.lims.dms.controller.exam.service.QuestionImportService;
import com.tianyuan.lims.dms.entity.LimsCategory;
import com.tianyuan.lims.dms.entity.LimsExamQuestion;
import com.tianyuan.lims.dms.entity.LimsExamRecord;
import com.tianyuan.lims.dms.entity.ZbtProductWty;
import com.tianyuan.lims.erp.admin.entity.AdminUser;
import com.tianyuan.lims.utils.BaseUtil;
import com.tianyuan.lims.utils.R;
import com.tianyuan.lims.utils.SqlUtils;
import io.github.yedaxia.apidocs.ApiDoc;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import static dm.jdbc.util.DriverUtil.log;

public class LimsExamController extends Controller {

    private final ExamRecordService examRecordService = new ExamRecordService();

    @ApiDoc(url = "/LimsExam/savePaper", method = "post")
    public void savePaper(@RequestBody LimsExamRecord request) {
        try {
            //LimsExamRecord record = limsExamRecordService.savePaper(request);
            renderJson(R.ok("试卷保存成功"));
        } catch (Exception e) {
            log.error("保存试卷失败", e);
            renderJson(R.error("保存试卷失败: " + e.getMessage()));
        }
    }

    @ApiDoc(url = "/LimsExam/generatePaper", method = "post")
    public void generatePaper() {
        try {
            AdminUser user = getSessionAttr("user");
            if (user == null) {
                renderJson(R.error("请先登录！"));
            }
            String data = getRawData();
            GeneratePaperRequest request = JSON.parseObject(data, GeneratePaperRequest.class);
            if (request.getQuestionCount() < 10 || request.getQuestionCount() > 200) {
                renderJson(R.error("题目数量必须在10-200之间! " ));
            }
            if (request.getKnowledgeConfig() == null || request.getKnowledgeConfig().isEmpty()) {
                renderJson(R.error("请选择至少一个知识点! " ));
            }
            double totalWeight = request.getKnowledgeConfig().stream()
                    .mapToDouble(KnowledgeConfig::getWeight)
                    .sum();
            if (Math.abs(totalWeight - 100.0) > 0.1) {
                renderJson(R.error("知识点权重总和必须为100%! " ));
            }
            PaperGenerateResult result = examRecordService.generatePaper(request);

            Map<String, Object> saveData = new HashMap<>();


            saveData.put("questiondata", result.getQuestionData());
            saveData.put("ext_json", JSON.toJSONString(request));
            if(user != null){
                saveData.put("user_id", user.getUserId());
            }



            examRecordService.savePaper(saveData);
            renderJson(R.ok("试卷保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成试卷失败", e);
            renderJson(R.error("保存试卷失败: " + e.getMessage()));
        }
    }


    /**
     * 获取我的考试记录列表
     */
    public void getMyExamRecords() {
        try {
            Long userId = getParaToLong("userId");
            if (userId == null) {
                renderJson(R.error("用户ID不能为空"));
                return;
            }
            List<Record> records = examRecordService.getUserExamRecords(userId);
            for (int i = 0; i < records.size(); i++) {
                Record record = records.get(i);
                //GeneratePaperRequest request = JSON.parseObject(record.get("ext_json"), GeneratePaperRequest.class);
                examRecordService.parseExtJsonData(record);
            }


            renderJson(R.ok().put("data", records));
        } catch (Exception e) {
            renderJson(R.error( "获取考试记录失败"));
        }
    }






    /**
     * 开始考试 - 创建考试记录
     */
    public void startExam() {
        try {
            Long userId = getParaToLong("userId");
            Integer bankId = getParaToInt("bankId");

            if (userId == null || bankId == null) {
                renderJson(R.error( "参数不能为空"));
                return;
            }

            // 检查是否已有未完成的考试记录
            Record existingRecord = examRecordService.getUnfinishedExam(userId, bankId);
            if (existingRecord != null) {
                renderJson(R.ok().put("data", existingRecord).put("msg", "继续未完成考试"));
                return;
            }

            // 创建新的考试记录
            Record examRecord = examRecordService.createExamRecord(userId, bankId);
            renderJson(R.ok().put("data", examRecord).put("msg", "开始新考试"));
        } catch (Exception e) {
            renderJson(R.error("开始考试失败"));
        }
    }

    /**
     * 获取考试详情
     */
    public void getExamDetail() {
        try {
            Integer recordId = getParaToInt("recordId");
            if (recordId == null) {
                renderJson(Ret.fail("msg", "考试记录ID不能为空"));
                return;
            }
            ExamDetailVO examDetailRes = new ExamDetailVO();
            Record examDetail = examRecordService.getExamDetail(recordId);
            if (examDetail == null) {
                renderJson(Ret.fail("msg", "考试记录不存在"));
                return;
            }
            String questiondata = examDetail.get("questiondata");
            if (questiondata != null && !questiondata.isEmpty()) {
                Map<String, Object> questionData = JSON.parseObject(questiondata, Map.class);
                if (questionData != null && questionData.containsKey("singleIds")) {
                    List<Long> singleIdList = (List<Long>) questionData.get("singleIds");
                    List<LimsExamQuestion> allQuestions = new ArrayList<>();
                    if (singleIdList != null && !singleIdList.isEmpty()) {
                        String sql = "SELECT * FROM lims_exam_question WHERE id IN (" +
                                SqlUtils.getPlaceholders(singleIdList.size()) + ")";
                        allQuestions = LimsExamQuestion.dao.find(sql, singleIdList.toArray());
                    }

                    // 使用 Stream 将 allQuestions 转换为 answeredQuestions
                    List<QuestionAnswer> answeredQuestions = allQuestions.stream()
                            .map(question -> {
                                QuestionAnswer answer = new QuestionAnswer();
                                answer.setQuestionId(question.getId());
                                answer.setUserAnswer(question.getAnswer()); // 如果是正确答案
                                return answer;
                            })
                            .collect(Collectors.toList());

                    examDetailRes.setRecordId((long)recordId);
                    examDetailRes.setQuestions(allQuestions);
                    examDetailRes.setAnsweredQuestions(answeredQuestions);
                    examDetailRes.setTotalQuestions(allQuestions.size());
                }
                renderJson(Ret.ok("data", examDetailRes));
            }
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(Ret.fail("msg", "获取考试详情失败"));
        }
    }







    /**
     * 提交考试
     */
    @ApiDoc(url = "/LimsExam/submitExam", method = "post")
    public void submitExam() {
        try {



//            SubmitExamRequest request = getBean(SubmitExamRequest.class);
            String data = getRawData();
            SubmitExamRequest request = JSON.parseObject(data, SubmitExamRequest.class);


            if (request.getRecordId() == null) {
                renderJson(R.error("考试记录ID不能为空"));
                return;
            }

            // 获取考试记录
            LimsExamRecord examRecord = LimsExamRecord.dao.findById(request.getRecordId());
            if (examRecord == null) {
                renderJson(R.error("考试记录不存在"));
                return;
            }

            // 检查是否已经提交过
//            if (examRecord.getStatus() == 1) {
//                renderJson(R.error("考试已提交，请勿重复提交"));
//                return;
//            }

            // 计算得分
            ExamResult examResult = calculateScore(request.getAnswers());

            // 更新考试记录
            //examRecord.setStatus(1); // 1表示已提交
            examRecord.setScore(examResult.getScore());
            examRecord.setSeconds(request.getSeconds());
            examRecord.setCreateTime(new Date());
            examRecord.setResult(JSON.toJSONString(request.getAnswers()));
            examRecord.update();

            // 返回考试结果
            Map<String, Object> result = new HashMap<>();
            result.put("recordId", examRecord.getId());
            result.put("score", examResult.getScore());
            result.put("totalQuestions", examResult.getTotalQuestions());
            result.put("correctCount", examResult.getCorrectCount());
            result.put("submitTime", new Date());

            renderJson(R.ok().put("data", result).put("msg", "考试提交成功"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("提交考试失败", e);
            renderJson(R.error("提交考试失败: " + e.getMessage()));
        }
    }

    /**
     * 自动保存考试进度
     */
    @ApiDoc(url = "/LimsExam/autoSave", method = "post")
    public void autoSave(@RequestBody AutoSaveRequest request) {
        try {
            if (request.getRecordId() == null) {
                renderJson(R.error("考试记录ID不能为空"));
                return;
            }

            // 获取考试记录
            LimsExamRecord examRecord = LimsExamRecord.dao.findById(request.getRecordId());
            if (examRecord == null) {
                renderJson(R.error("考试记录不存在"));
                return;
            }

            // 检查是否已经提交
//            if (examRecord.getStatus() == 1) {
//                renderJson(R.error("考试已提交，无法自动保存"));
//                return;
//            }

            // 更新自动保存数据
            Map<String, Object> autoSaveData = new HashMap<>();
            autoSaveData.put("answers", request.getAnswers());
            autoSaveData.put("currentQuestion", request.getCurrentQuestion());
            autoSaveData.put("remainingTime", request.getRemainingTime());
            autoSaveData.put("lastSaveTime", new Date());


            Map<String, String> answers = request.getAnswers();
            examRecord.setResult(JSON.toJSONString(answers));

//            examRecord.setAutoSaveData(JSON.toJSONString(autoSaveData));
//            examRecord.setUpdateTime(new Date());
            examRecord.update();

            renderJson(R.ok("自动保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("自动保存失败", e);
            renderJson(R.error("自动保存失败: " + e.getMessage()));
        }
    }

    /**
     * 计算考试得分
     */
    private ExamResult calculateScore(List<QuestionAnswer> userAnswers) {
        if (userAnswers == null || userAnswers.isEmpty()) {
            return new ExamResult(0, 0, 0);
        }

        int correctCount = 0;
        int totalQuestions = userAnswers.size();

        for (QuestionAnswer userAnswer : userAnswers) {
            // 获取题目正确答案
            LimsExamQuestion question = LimsExamQuestion.dao.findById(userAnswer.getQuestionId());
            if (question != null && question.getAnswer() != null) {
                // 比较用户答案和正确答案
                if (question.getAnswer().equalsIgnoreCase(userAnswer.getUserAnswer())) {
                    correctCount++;
                }
            }
        }

        // 计算分数（百分制）
        double score = totalQuestions > 0 ? (correctCount * 100.0) / totalQuestions : 0;

        ExamResult result = new ExamResult();
        result.setScore(Math.round(score * 100) / 100.0); // 保留两位小数
        result.setTotalQuestions(totalQuestions);
        result.setCorrectCount(correctCount);

        return result;
    }
}
